import { reactive } from "vue"
import { todayPost, thisWeek, thisMonth } from "@/mock"
import { Post,User } from "@/types"
import axios from "axios"

/**
 * prop{
 * id:{},
 * id:{}, 
 * id:{}
 * @description 模拟vuex 
 * }
 */

interface PostState {
    ids: string[],
    all: Record<string, Post> //前面的类型专户为后面的类型
    loaded: boolean //判断是否有加载数据 加载的状态
}

interface LoginUserState {
    ids: string[],
    all: Record<string, Post> //前面的类型专户为后面的类型
    loaded: boolean, //判断是否有加载数据 加载的状态
    currentUserId?:string
}


const initialPostState = (): PostState => ({
    ids: [
        // todayPost.id.toString(),
        // thisWeek.id.toString(),
        // thisMonth.id.toString(),

    ],
    all: {
        // [todayPost.id]:todayPost,
        // [thisWeek.id]:thisWeek,
        // [thisMonth.id]:thisMonth,
    },
    loaded: false
})

const initialLoginUserState = (): LoginUserState => ({
    ids: [
        // todayPost.id.toString(),
        // thisWeek.id.toString(),
        // thisMonth.id.toString(),

    ],
    all: {
        // [todayPost.id]:todayPost,
        // [thisWeek.id]:thisWeek,
        // [thisMonth.id]:thisMonth,
    },
    loaded: false,
    currentUserId:undefined

})

interface State {
    posts: PostState,
    loginUser:LoginUserState
}

const initialState = (): State => ({
    posts: initialPostState(),
    loginUser:initialLoginUserState()
})



class Store {
    protected state: State
    constructor(initialState: State) {
        this.state = reactive(initialState)
    }
    public getState(): State {
        return this.state
    }
    async fetchPosts(){
        const response=await axios.get<Post[]>("/posts");
        // 数据处理
      
        const ids:string[]=[]
        const all:Record<string,Post>={}
        for(const post of response.data){
            if(!this.state.posts.ids.includes(post.id.toString())){
                this.state.posts.ids.push(post.id.toString());
            this.state.posts.all[post.id]=post
            }
        }
        this.state.posts.loaded=true
    }
    async cteatePosts(post:Post){
        const response=await axios.post<Post>("/posts",post);
        // 数据处理
        this.state.posts.all[response.data.id]=response.data;
        this.state.posts.ids.push(response.data.id.toString());
    }
    async updatePosts(post:Post){
        const response=await axios.put<Post>("/posts",post);
        // 数据处理
        this.state.posts.all[response.data.id]=response.data;
    }

    async createUser(user:User){
    //    创建用户
    const response=await axios.post<any>("/users",user);
    // 数据处理
    this.state.loginUser.all[response.data.id]=response.data;
    this.state.loginUser.ids.push(response.data.id.toString());
    this.state.loginUser.currentUserId=response.data.id.toString();
    console.log(this.state.loginUser)
    }

    async signOut(){
        this.state.loginUser.currentUserId=undefined;
    }
}
const store = new Store(initialState())

export const useStore = () => store;